<template>
  <div class="common-layout" v-loading="loading">
    <el-container>
      <el-header>
        <el-form :inline="true" :model="examList" class="demo-form-inline" :rules="rules">
          <el-form-item label="考试名称" prop="examName"  style="width: 190px">
            <el-input  placeholder="请输入考试名称" v-model="examList.examName" clearable />
          </el-form-item>
          <el-form-item label="考试时间" prop="examStartTime">
            <el-date-picker
                v-model="examList.examStartTime"
                type="datetime"
                style="width: 150px"
                placeholder="请输入考试开始时间"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="考试时长" style="width: 230px" prop="duration" >
            <el-input placeholder="请输入考试时长(分钟)" v-model="examList.duration" type="number" clearable />
          </el-form-item>
          <el-form-item  style="width: 350px">
            单选题{{countList.radio}}&nbsp&nbsp;多选题{{countList.checkbox}}&nbsp;|&nbsp;判断题{{countList.judge}}&nbsp;|&nbsp;简答题{{countList.answer}}&nbsp;|&nbsp;总分{{countList.score}}分
          </el-form-item>
        </el-form>
      </el-header>
      <el-container>
        <el-aside>
          <div style="text-align: center;background-color:rgb(241, 243, 248);height: 20px;padding-bottom: 10px;padding-top: 10px;font-size: 20px">可以拖拽来改变题目的顺序</div>
            <VueDraggable
                ref="el"
                v-model="examList.list"
                class="ghost"
                @end="saveAnswer"
            >
              <div v-for="(item,index) in examList.list"
                   :key="item.id"
                   style="padding: 10px 10px 10px 10px;text-align: center"
                  >
                 {{index+1}}.{{ item.questionTitle }}
              </div>
            </VueDraggable>
          <el-button type="primary" style="margin-top:20px" @click="addExam">发布试卷<el-icon><Position></Position></el-icon></el-button>
        </el-aside>
        <el-main>
          <div>
            <el-empty description="请添加题目" v-if="examList.list.length===0"/>
            <div v-for="(item,index) in examList.list" v-if="answerList.length>0">
              <div style="padding: 10px 10px 10px 10px;" v-if="item.questionType==='0'">
                <div>
                  {{index+1}}.单选题
                  <div style="float: right;"><Delete style="width: 1.5em; height: 1.5em; margin-right: 8px" @click="deleteQuestion(index)"/></div>
                </div>
                <el-input
                    v-model="item.questionTitle"
                    style="width: 100%"
                    placeholder="请输入题干内容（必填）"
                    show-word-limit
                    type="textarea"
                />
                <div style="margin-top: 10px">
                  <el-radio-group v-model="answerList[index][0]" @change="updateCorrectRadio(item,index)" v-if="item.options.length>0">
                        <el-radio value="0">A
                          <el-input
                              v-model="item.options[0].optionText"
                              style="width: 280px"
                              placeholder="请输入选项;选中及设置为正确答案（必填）"
                              show-word-limit
                              type="text"
                          />
                        </el-radio>
                        <el-radio value="1">B
                          <el-input
                              v-model="item.options[1].optionText"
                              style="width: 280px"
                              placeholder="请输入选项;选中及设置为正确答案（必填）"
                              show-word-limit
                              type="text"
                          />
                        </el-radio>
                        <el-radio value="2">C
                          <el-input
                              v-model="item.options[2].optionText"
                              style="width: 280px"
                              placeholder="请输入选项;选中及设置为正确答案（必填）"
                              show-word-limit
                              type="text"
                          />
                        </el-radio>
                        <el-radio value="3">D
                          <el-input
                              v-model="item.options[3].optionText"
                              style="width: 280px"
                              placeholder="请输入选项;选中及设置为正确答案（必填）"
                              show-word-limit
                              type="text"
                          />
                        </el-radio>
                  </el-radio-group>
                  <div style="margin-top: 20px">
                    分数：<el-input-number :min="0" max="20" v-model="item.score"  @change="totalScore" /></div>
                  </div>
              </div>
              <div style="padding: 10px 10px 10px 10px;" v-else-if="item.questionType==='1'">
                {{index+1}}.多选题
                <div style="float: right;"><Delete style="width: 1.5em; height: 1.5em; margin-right: 8px" @click="deleteQuestion(index)"/></div>
                <el-input
                    v-model="item.questionTitle"
                    style="width: 100%"
                    placeholder="请输入题干内容（必填）"
                    show-word-limit
                    type="textarea"
                />
                <div style="margin-top: 10px">
                  <el-checkbox-group v-model="answerList[index]" @change="updateCorrectCheckbox(item,index)" v-if="item.options.length>0">
                    <el-checkbox  value="0" >A
                      <el-input
                          v-model="item.options[0].optionText"
                          style="width: 280px"
                          placeholder="请输入选项;选中及设置为正确答案（必填）"
                          show-word-limit
                          type="text"
                      />
                    </el-checkbox>
                    <el-checkbox  value="1" >B
                      <el-input
                          v-model="item.options[1].optionText"
                          style="width: 280px"
                          placeholder="请输入选项;选中及设置为正确答案（必填）"
                          show-word-limit
                          type="text"
                      />
                    </el-checkbox>
                    <el-checkbox  value="2" >C
                      <el-input
                          v-model="item.options[2].optionText"
                          style="width: 280px"
                          placeholder="请输入选项;选中及设置为正确答案（必填）"
                          show-word-limit
                          type="text"
                      />
                    </el-checkbox>
                    <el-checkbox  value="3">D
                    <el-input
                        v-model="item.options[3].optionText"
                        style="width: 280px"
                        placeholder="请输入选项;选中及设置为正确答案（必填）"
                        show-word-limit
                        type="text"
                    />
                    </el-checkbox>
                  </el-checkbox-group>
                  <div style="margin-top: 20px">
                    分数：<el-input-number :min="0" max="20" v-model="item.score"  @change="totalScore" /></div>
                </div>
              </div>
              <div style="padding: 10px 10px 10px 10px;" v-else-if="item.questionType==='2'">
                {{index+1}}.判断选题
                <div style="float: right;"><Delete style="width: 1.5em; height: 1.5em; margin-right: 8px" @click="deleteQuestion(index)"/></div>
                <el-input
                    v-model="item.questionTitle"
                    style="width: 100%"
                    placeholder="请输入题干内容（必填）"
                    show-word-limit
                    type="textarea"
                />
                <div style="margin-top: 10px">
                  <el-radio-group v-model="answerList[index][0]" @change="updateCorrectRadio(item,index)" v-if="item.options.length>0">
                    <el-radio value="0" >A
                      <el-input
                          disabled
                          style="width: 280px"
                          placeholder="正确"
                          show-word-limit
                          type="text"
                      />
                    </el-radio>
                    <el-radio value="1">B
                      <el-input
                          disabled
                          style="width: 280px"
                          placeholder="错误"
                          show-word-limit
                          type="text"
                      />
                    </el-radio>
                  </el-radio-group>
                  <div style="margin-top: 20px">
                    分数：<el-input-number :min="0" max="20"  v-model="item.score"  @change="totalScore" /></div>
                </div>
              </div>
              <div style="padding: 10px 10px 10px 10px;" v-else>
                {{index+1}}.主观题
                <div style="float: right;"><Delete style="width: 1.5em; height: 1.5em; margin-right: 8px" @click="deleteQuestion(index)"/></div>
                <el-input
                    v-model="item.questionTitle"
                    style="width: 100%"
                    placeholder="请输入题干内容（必填）"
                    show-word-limit
                    type="textarea"
                />
                <div style="margin-top: 10px">
                  <el-input
                  v-model="item.answerContent"
                  style="width: 600px"
                  placeholder="请输入参考答案（必填）"
                  show-word-limit
                  type="text"
                  />
                  <div style="margin-top: 20px">
                    分数：<el-input-number :min="0" max="50" v-model="item.score"  @change="totalScore" /></div>
                </div>
              </div>
            </div>
          <div>
            <el-dropdown @command="addQuestion">
              <el-button type="primary">添加题目<el-icon ><CirclePlus></CirclePlus></el-icon></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="0">单选题</el-dropdown-item>
                  <el-dropdown-item command="1">多选题</el-dropdown-item>
                  <el-dropdown-item command="2">判断题</el-dropdown-item>
                  <el-dropdown-item command="3">主观题</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button type="primary" style="float: right;" @click="dialogFormVisible=true">从题库添加<el-icon ><CirclePlus></CirclePlus></el-icon></el-button>
          </div>
          </div>
          <!--题库添加弹层-->
          <el-dialog v-model="dialogFormVisible" title="选择试题" width="1500px" v-if="dialogFormVisible">
            <div class="common-layout" v-show="showQuestion">
              <el-container>
                <el-aside width="150px">
                  <!-- 学科渲染开始 -->
                  <el-tree ref="treeRef" style="font-size: large; background-color: transparent;" :default-expanded-keys="[0]"
                           :default-checked-keys="[0]" :data="data" node-key="id" :props="defaultProps" @node-click="handleNodeClick" />
                  <!-- 学科渲染结束 -->
                </el-aside>
                <el-main>
                  <!-- 题库渲染开始 -->
                  <el-table ref="multipleTableRef" border v-loading="loading" row-key="sid" style="width: 100%" :data="tableData">
                    <el-table-column property="name" label="题库名称" min-width="100" width="200" show-overflow-tooltip
                                     align="left" />
                    <el-table-column property="description" label="描述" show-overflow-tooltip align="center" />
                    <el-table-column property="createTime" label="创建时间" min-width="173" width="173" align="center" />
                    <el-table-column label="操作" fixed="right" width="200" align="center">
                      <template v-slot="scope">
                        <el-link type="primary" icon="View" style="margin-right: 10px" @click="look(scope.row)">
                          查看题目
                        </el-link>
                      </template>
                    </el-table-column>
                  </el-table>
                  <!-- 题库渲染结束 -->
                  <!-- 分页开始 -->
                  <br>
                  <el-pagination v-model:current-page="page" v-model:page-size="size" :page-sizes="[5, 10, 15, 20]"
                                 :background="true" layout="total, sizes, prev, pager, next" :total="total" @size-change="handleSizeChange"
                                 @current-change="handleCurrentChange" />
                  <!-- 分页结束 -->
                </el-main>
              </el-container>
            </div>
            <div class="common-layout" v-show="!showQuestion">
              <el-form-item>
                 <el-button icon="ArrowLeft" @click="showQuestion=true">返回题库</el-button>
                 <div style="float: right;margin-left: 10px;font-size: 20px;color: red">勾选✔方框就是添加题目的操作，这里只能添加题目，想要删除题库添加的题目，关闭这个窗口，去创建试卷页面，点击垃圾桶就可以啦</div>
              </el-form-item>
                  <!-- 列表渲染开始 -->
                  <el-table ref="multipleTableRef" v-loading="loading" style="width: 100%;" height="400px"  border :data="questionData"
                            @selection-change="handleSelectionChange" >
                    <el-table-column type="selection" width="55" align="center" :selectable="selectTable" />
                    <el-table-column property="id" label="题号" width="55" align="center" />
                    <el-table-column property="questionTitle" label="题目名称" min-width="180" show-overflow-tooltip align="center" />
                    <el-table-column property="analysis" label="题目解析" min-width="180" show-overflow-tooltip align="center" />
                    <el-table-column label="题目类型" width="75" align="center">
                      <template v-slot="scope">
                        <el-tag type="success">
                          {{ scope.row.questionType == 0 ? "单选" :
                            scope.row.questionType == 1 ? "多选" :
                                scope.row.questionType == 2 ? "判断" :
                                    scope.row.questionType == 3 ? "主观题" : "编程题"
                          }}
                        </el-tag>
                      </template>
                    </el-table-column>
                  </el-table>
                  <!-- 列表渲染结束 -->
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import {nextTick, onMounted, ref, watch} from 'vue'
import { VueDraggable } from 'vue-draggable-plus'
import {CirclePlus, Delete, Position} from "@element-plus/icons-vue";
import {useStaffStore} from "@/stores/staff.js";
import axios from "@/axios/index.js";
import {ElMessage} from "element-plus";
import axiosInstance from "@/axios/index.js";
import router from "@/router";

const qbid = ref()//题库id
let questionData = ref([])
//获取题目列表
let getQuestionsList = function ( questionBanksId) {
  axios.get(`/api/v1/admin/questions`, {
    params: {
      page:-1,
      size:-1,
      questionBanksId,
      status:1
    }
  }).then(response => {
    questionData.value = response.data.data.data
    total.value = response.data.data.total
  })
}

const multipleTableRef=ref({})
//多选框选中集合
const multipleSelection = ref([])
//多选框选中集合
const selectTable=(row)=>!multipleSelection.value.includes(row.id)
//多选框长度记录
let length =ref(0)
//当多选框发生变化
const handleSelectionChange = (val) => {
  multipleSelection.value=val.map(item =>item.id)
  if (val.length-length.value===questionData.value.length){
    for (let i = 0; i < multipleSelection.value.length; i++) {
      axiosInstance.get(`/api/v1/admin/questions/id/${multipleSelection.value[i]}`).then(res => {
        getQuestion(res)
      })
    }
    ElMessage({
      message: `添加${questionData.value.length}条数据成功`,
      type: 'success',
    })
  }else {
    axiosInstance.get(`/api/v1/admin/questions/id/${multipleSelection.value[multipleSelection.value.length-1]}`).then(res => {
      getQuestion(res)
    })
    console.log(examList.value)
    ElMessage({
      message: '添加成功',
      type: 'success',
    })
  }
  if(length.value===questionData.value.length){
     length.value=0
  }else {
    length.value++
  }
}
//处理多选框选中题库题目
const getQuestion= function (res) {
  if (res.data.data.questionType==='0'){
    countList.value.radio++;
  }else if(res.data.data.questionType==='1'){
    countList.value.checkbox++;
  }else if(res.data.data.questionType==='2'){
    countList.value.judge++;
  }else{
    countList.value.answer++;
  }
  examList.value.list.push({
    questionTitle:res.data.data.questionTitle,
    score:0,
    questionType:res.data.data.questionType,
    createBy:res.data.data.staffId===null ? res.data.studentId:res.data.data.staffId,
    answerContent:'',
    options:[],
    id:''
  })
  if (res.data.data.questionType==="3"){
    answerList.value.push([])
    examList.value.list[examList.value.list.length-1].answerContent= res.data.data.options[0].optionDescribe
  }else {
    answerList.value.push([])
    for (let i = 0; i < res.data.data.options.length; i++) {
      examList.value.list[examList.value.list.length-1].options.push({
        optionText:res.data.data.options[i].optionDescribe,
        isCorrect:res.data.data.options[i].status,
        createBy:res.data.data.staffId===null ? res.data.studentId:res.data.data.staffId,
      })
      if(res.data.data.options[i].status===1){
        answerList.value[answerList.value.length-1].push(i+"")
      }
    }
  }
  examList.value.list[examList.value.list.length-1].id=res.data.data.id
}

//查看题目控制器
const showQuestion=ref(true)
let page = ref(1)
let size = ref(5)
let total = ref(10)
let tableData = ref([])//表格数据
let loading = ref(false)//加载动画
let subjectId = ref(0)//当前选中学科id
let data = ref([
  {
    id: 0,
    subjectName: '全部学科',
    children: []
  }
])//题库列表
let searchForm = ref({
  name: '',
  status: 1
})//题库搜索表单
const defaultProps = {
  label: 'subjectName',
  children: 'children'
}
//查询所有学科
let getSubjectList = function () {
  axios.get(`/api/v1/admin/subject/list`, {
    params: {
      currentPage: 1,
      pageSize: -1
    }
  }).then(response => {
    data.value[0].children = response.data.data.records
  })
}

//获取题库列表
let getQuestionsBankList = function (current, limit, sid, name, status) {
  if (current == -1 && limit == -1) {
    current = page.value
    limit = size.value
  }
  axios.get(`/api/v1/admin/question/banks`, {
    params: {
      page: current,
      size: limit,
      sid: sid,
      name: name,
      status: status
    }
  }).then(response => {
    total.value = response.data.data.total
    tableData.value = response.data.data.data
  })
}
const treeRef = ref()
onMounted(() => {
  getSubjectList()
  getQuestionsBankList(page.value, size.value, 1)
})

//查看题目
let look = function (form) {
  showQuestion.value= false
  qbid.value = form.id
  getQuestionsList(form.id)
}
//当节点被点击时触发
const handleNodeClick = (data) => {
  subjectId.value = data.id
  getQuestionsBankList(page.value, size.value, data.id, null, 1)
}
//当page发生变化时触发
const handleCurrentChange = (val) => {
  getQuestionsBankList(val, size.value, subjectId.value, searchForm.value.name, searchForm.value.status)
}
//当size发生变化时触发
const handleSizeChange = (val) => {
  getQuestionsBankList(page.value, val, subjectId.value, searchForm.value.name, searchForm.value.status)
}

//题库添加状态控制
const dialogFormVisible = ref(false)

watch(dialogFormVisible,()=>{
  nextTick(() => {
    const tree = treeRef.value
    if (tree) {
      // 获取第一个节点（假设你想点击的是 id 为 1 的节点）
      const node = tree.getNode(1)
      if (node) {
        // 设置当前节点并手动触发点击事件
        tree.setCurrentKey(1)
        // 如果你需要确保点击事件处理函数被调用，也可以手动调用它
        handleNodeClick(node.data)
      }
    }
  })
})
//试卷基本信息校验规则
const rules = ref({
  examName: [{ required: true, message: '请输入考试名称', trigger: 'blur' }],
  examStartTime: [{ required: true, message: '请输入考试开始时间', trigger: 'blur' }],
  duration: [
    { required: true, message: '请输入考试时间', trigger: 'blur' },
    {min: 1, message: '考试时间不能小于1分钟', trigger: 'blur' }
  ],
})
//统计列表
const countList = ref({
  radio:0,
  checkbox:0,
  judge:0,
  answer:0,
  score:0
})
//单选答案列表
const answerList = ref([])
//试卷列表
const examList = ref({
  examName:null,
  examStartTime: null,
  duration:null,
  examEndTime:null,
  examType:1,
  classId:localStorage.getItem("classId"),
  createBy:useStaffStore().staffInfo.staff.id,
  list:[],
})
//添加题目
const addQuestion = (command)=>{
  examList.value.list.push({
    questionTitle:"",
    score:0,
    questionType:command,
    createBy:useStaffStore().staffInfo.staff.id,
    answerContent:'',
    options:[]
  })
  if (command==='0'){
    countList.value.radio++;
    answerList.value.push(["0"])
    examList.value.list[examList.value.list.length-1].options.push({
      optionText:"",
      isCorrect:1,
      createBy:useStaffStore().staffInfo.staff.id
    })
    examList.value.list[examList.value.list.length-1].options.push({
      optionText:"",
      isCorrect:0,
      createBy:useStaffStore().staffInfo.staff.id
    })
    examList.value.list[examList.value.list.length-1].options.push({
      optionText:"",
      isCorrect:0,
      createBy:useStaffStore().staffInfo.staff.id
    })
    examList.value.list[examList.value.list.length-1].options.push({
      optionText:"",
      isCorrect:0,
      createBy:useStaffStore().staffInfo.staff.id
    })
  }else if(command==='1'){
    countList.value.checkbox++;
    answerList.value.push(["0"])
    examList.value.list[examList.value.list.length-1].options.push({
      optionText:"",
      isCorrect:1,
      createBy:useStaffStore().staffInfo.staff.id
    })
    examList.value.list[examList.value.list.length-1].options.push({
      optionText:"",
      isCorrect:0,
      createBy:useStaffStore().staffInfo.staff.id
    })
    examList.value.list[examList.value.list.length-1].options.push({
      optionText:"",
      isCorrect:0,
      createBy:useStaffStore().staffInfo.staff.id
    })
    examList.value.list[examList.value.list.length-1].options.push({
      optionText:"",
      isCorrect:0,
      createBy:useStaffStore().staffInfo.staff.id
    })
  }else if(command==='2'){
    countList.value.judge++;
    answerList.value.push(["0"])
    examList.value.list[examList.value.list.length-1].options.push({
      optionText:"正确",
      isCorrect:1,
      createBy:useStaffStore().staffInfo.staff.id
    })
    examList.value.list[examList.value.list.length-1].options.push({
      optionText:"错误",
      isCorrect:0,
      createBy:useStaffStore().staffInfo.staff.id
    })
  }else{
    countList.value.answer++;
    answerList.value.push([])
  }
}
//删除题目
const deleteQuestion = (index)=>{
  if (examList.value.list[index].questionType==='0'){
    countList.value.radio--;
  }else if(examList.value.list[index].questionType==='1'){
    countList.value.checkbox--;
  }else if(examList.value.list[index].questionType==='2'){
    countList.value.judge--;
  }else{
    countList.value.answer--;
  }
  if(examList.value.list[index].hasOwnProperty("id")){
    multipleSelection.value.splice(multipleSelection.value.indexOf(examList.value.list[index].id),1)
    examList.value.list.splice(index,1)
  }else {
    examList.value.list.splice(index,1)
  }
  totalScore()
}

//计算题库分数
const totalScore=()=>{
  countList.value.score=0
  examList.value.list.forEach(item=>{
    countList.value.score+=item.score
  })
}
//单选答案
const updateCorrectRadio=(item,index)=> {
  item.options.forEach((option) => {
    if (option.isCorrect === 1) {
      option.isCorrect = 0
    }
  })
  item.options[answerList.value[index]].isCorrect = 1
}
//确认多选题目答案
const updateCorrectCheckbox=(item,index)=>{
  item.options.forEach((option) => {
    if (option.isCorrect === 1) {
      option.isCorrect = 0
    }
  })
  for (let i = 0; i < answerList.value[index].length; i++) {
    item.options[answerList.value[index][i]].isCorrect=1
  }
}
//发布试卷
const addExam=()=>{
  if(examList.value.examStartTime===null||examList.value.duration===null||examList.value.examName===null){
    ElMessage({
      message: '请按要求填写试卷的基本信息',
      type: 'error',
    })
  }else {
    if(examList.value.list.length===0){
      ElMessage({
        message: '请添加题目在提交',
        type: 'error',
      })
    }else {
      if(examList.value.duration===''){
        ElMessage({
          message: '请添加考试时长再提交',
          type: 'error',
        })
      }else {
        let date= new Date(new Date(examList.value.examStartTime).getTime() + (Number.parseInt(examList.value.duration)* 60000));
        // 格式化为所需的字符串
        examList.value.examEndTime = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
        loading.value=true
        examList.value.list.forEach((item)=>{
          if(item.hasOwnProperty("id")){
              delete item.id
          }
        })
        axiosInstance.post("/examRecords/addExam",JSON.stringify(examList.value),{ headers: {"Content-Type": "application/json"}}).then(res=> {
          if (res.data.code === 200) {
            ElMessage({
              message: '试卷发布成功',
              type: 'success',
            })
            loading.value=false
            router.push({path: '/classManagement/exam'})
          }else {
            ElMessage({
              message: res.data.message,
              type: 'error',
            })
            loading.value=false
          }
        })
      }
    }
  }
}

//将答案列表储存到题目列表
const saveAnswer=()=>{
  let options=[]
  answerList.value=[]
  for (let i = 0; i < examList.value.list.length; i++) {
    if(examList.value.list[i].options.length!==0){
      for (let j = 0; j < examList.value.list[i].options.length; j++) {
        if (examList.value.list[i].options[j].isCorrect === 1) {
          options.push(j + '')
        }
      }
      answerList.value.push(options)
      options=[]
    }else {
      answerList.value.push([])
    }
  }
}
</script>

<style scoped>
.ghost {
  opacity: 0.5;
  background-color:rgb(241, 243, 248)
}

.infinite-list {
  height: 300px;
  padding: 0;
  margin: 0;
  list-style: none;
}
.infinite-list .infinite-list-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  background: var(--el-color-primary-light-9);
  margin: 10px;
  color: var(--el-color-primary);
}
.infinite-list .infinite-list-item + .list-item {
  margin-top: 10px;
}
</style>
